# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:   smalleel-api-tools
# FileName:     jsonUtil.py
# Author:
# Datetime:    2022/4/6 14:29
# Description：读取sql文件,获取json内容
# -----------------------------------------------------------------------------------
import json
from json import JSONDecodeError
from common.util.configUtil.configUtil import ConfigUtil

config = ConfigUtil()


def read_sql_json(sqlApiKey: str, sqlQureyKey: str, systemType: int = 1, *kwargs) -> str:
    """
    读取sql语句
    :param systemType:
                        1:电表
                        2:物业小程序
                        3:商户小程序
                        4:水表
                        5:暖通空调
    :param sqlApiKey: 需要读取的sql文件中所属功能的key值
    :param sqlQureyKey: sql语句的key值
    :return: sql语句
    """
    if systemType == 1:
        fileName = config.get_json_path("smalleelSqlFile")
    elif systemType == 2:
        fileName = config.get_json_path("merchantSqlFile")
    elif systemType == 3:
        fileName = config.get_json_path("tenantSqlFile")
    elif systemType == 4:
        fileName = config.get_json_path("waterSqlFile")
    elif systemType == 5:
        fileName = config.get_json_path("hvacSqlFile")
    elif systemType == 6:
        fileName = config.get_json_path("publicInterFaceSqlFile")
    else:
        raise "暂无该系统的SQL文件！"
    with open(fileName.strip(), encoding="utf-8") as data:
        sqlData = json.load(data)
        if kwargs is None:
            return sqlData[sqlApiKey.strip()][sqlQureyKey.strip()]
        else:
            return sqlData[sqlApiKey.strip()][sqlQureyKey.strip()].format(*kwargs, *kwargs, *kwargs, *kwargs)


def system_choose(systemType: int) -> str:
    """
    选择操作端
    :param systemType:
                        1:电表
                        2:物业小程序
                        3:商户小程序
                        4:水表
                        5:暖通空调
    :return: 各个端的token，opt，proid存放路径
    """

    if systemType == 1:
        return config.get_json_path("smalleelExtract")
    elif systemType == 2:
        return config.get_json_path("merchantExtract")
    elif systemType == 3:
        return config.get_json_path("tenantExtract")
    elif systemType == 4:
        return config.get_json_path("waterExtract")
    elif systemType == 5:
        return config.get_json_path("hvacExtract")
    elif systemType == 6:
        return config.get_json_path("platformExtract")
    else:
        raise "暂无该系统"


def read_extract_json(key: str, systemType: int = 1) -> str:
    """
    读取token,opt,proid json文件
    :param systemType:
                        1:电表
                        2:物业小程序
                        3:商户小程序
                        4:水表
                        5:暖通空调
    :param key: 需要读取的extract文件的key值
    :return: sql语句
    """
    try:
        with open(system_choose(systemType).strip(), encoding="utf-8") as data:
            extractData = json.load(data)
        return extractData[key]
    except JSONDecodeError:
        print("未获取到ExtractJson文件内容！")
        return


def write_json(data, systemType: int = 1) -> None:
    """
    写入json文件
    :param data: 写入的数据(登录数据)
    :param systemType: 系统类型
    :return:
    """

    with open(system_choose(systemType), mode='w', encoding='utf-8') as f:
        f.write(json.dumps(data, ensure_ascii=False))


def write_auxiliary_json(data):
    """
        写入json文件
        :param data: 写入的数据（备用数据）
        :param systemType: 系统类型
        :return:
        """
    file_path = config.get_json_path("group_param_auxiliary")
    with open(file_path, mode='w', encoding='utf-8') as f:
        f.write(json.dumps(data, ensure_ascii=False))


def public_read_json(fileName: str, *args) -> [str, dict]:
    """
    读取json文件
    :param fileName: 文件名
    :param args: 需要读取的文件的key值
    :return: sql语句
    """
    filePath = config.get_json_path(fileName)
    with open(filePath.strip(), encoding="utf-8") as data:
        extractData = json.load(data)
    if args == ():
        return extractData
    else:
        return extractData[args[0]]


def public_write_json(data, fileName) -> None:
    """
    写入json文件
    :param data: 写入的数据
    :param fileName:文件名
    :return:
    """
    filePath = config.get_json_path(fileName)
    with open(filePath, mode='w', encoding='utf-8') as f:
        f.write(json.dumps(data, ensure_ascii=False))


if __name__ == '__main__':
    # print(read_extract_json("token", 4))
    # print(read_sql_json('getquotaapplyaid', 'commitapplyquota', 1, read_extract_json('proid')))
    # print(read_sql_json('getquotaapplyaid', 'getQuotaMonth', 1, read_extract_json('proid')))
    # print(read_extract_json("token", 2))
    print(read_sql_json('openapi_sql', 'companySecret', 6, "测试公司移动到区域"))
